import React, { useRef, useEffect } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

interface Props {
  imageUrl: string;
}

const Sphere: React.FC<Props> = ({ imageUrl }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const requestRef = useRef<number | null>(null);
  const previousTimeRef = useRef<number | null>(null);
  const sphereRef = useRef<THREE.Mesh | null>(null);
  const controlsRef = useRef<OrbitControls | null>(null);

  useEffect(() => {
    // 创建场景
    const scene = new THREE.Scene();

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      75,
      containerRef.current!.clientWidth / containerRef.current!.clientHeight,
      0.1,
      1000
    );
    camera.position.z = 3;

    // 创建渲染器
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setClearColor("#02004D");
    renderer.setSize(
      containerRef.current!.clientWidth,
      containerRef.current!.clientHeight
    );
    containerRef.current!.appendChild(renderer.domElement);

    // 加载纹理
    const texture = new THREE.TextureLoader().load(imageUrl);

    // 创建材质
    const material = new THREE.MeshBasicMaterial({ map: texture });

    // 创建球体
    const geometry = new THREE.SphereGeometry(1, 32, 32);
    const sphere = new THREE.Mesh(geometry, material);
    scene.add(sphere);
    sphereRef.current = sphere;

    // 创建控制器
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.enableZoom = false;
    controlsRef.current = controls;

    // 动画函数
    const animate = (time: number) => {
      if (previousTimeRef.current !== null) {
        const deltaTime = time - previousTimeRef.current;

        // 自动旋转
        if (sphereRef.current) {
          sphereRef.current.rotation.y += 0.001 * deltaTime;
        }

        // 更新控制器
        if (controlsRef.current) {
          controlsRef.current.update();
        }
      }
      previousTimeRef.current = time;
      requestRef.current = requestAnimationFrame(animate);
      renderer.render(scene, camera);
    };

    // 开始动画
    requestRef.current = requestAnimationFrame(animate);

    // 组件销毁时停止动画
    return () => {
      if (requestRef.current) {
        cancelAnimationFrame(requestRef.current);
      }
    };
  }, [imageUrl]);

  return (
    <div
      ref={containerRef}
      style={{ width: "300px", height: "500px", margin: "auto" }}
    />
  );
};

export default Sphere;
